package com.spzx.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;
import com.spzx.product.helper.CategoryHelper;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类Service业务层处理
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private  CategoryMapper categoryMapper;

    /**
     * 商品分类Service业务层处理
     */
    @Override
    public List<Category> treeList(Long parentId) {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        if (!CollectionUtils.isEmpty(categoryList)){
            for (Category category : categoryList) {
                Long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
                category.setHasChildren(count>0);
            }
        }
        return categoryList;
    }

    /**
     * 根据分类id获取全部本级及上级节点id列表
     */
    @Override
    public List<Long> getAllCategoryIdList(Long id) {
        List<Long> idList=new ArrayList<>();
    List<Category> categoryList=    this.getPartentCategoryIdList(id,new ArrayList<Category>());
        int size = categoryList.size();
        for (int i = size-1; i >=0 ; i--) {
            Category category = categoryList.get(i);
            idList.add(category.getId());
        }
        return idList;
    }

    /*递归:根据本级分类id，查询本级分类及所有上级分类数据:存储，逆序
    1.三级找二级、二级找一级 过程是同样过程
    2.一级找父亲没有了就结束了*/
    private List<Category> getPartentCategoryIdList(Long id, ArrayList<Category> categoryList) {
        while (id>0){
            Category category = categoryMapper.selectById(id);  //本级
            categoryList.add(category);
            return  getPartentCategoryIdList(category.getParentId(),categoryList);
        }
        return  categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
try {
    //设置响应结果
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("UTF-8");

    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    String fileName = URLEncoder.encode("分类数据", "UTF-8");
    response.setHeader("Content-disposition","attachment;fileName="+fileName+".xlsx");
    response.setHeader("Access-Control-Expose-Headers","Content-Disposition");

    //查询数据库中的数据
    List<Category> categoryList = categoryMapper.selectList(null);
    List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());

    //将从数据库中查询到的Category对象转换成CategoryExceIVo对象
    for (Category category : categoryList) {
        CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
        BeanUtils.copyProperties(category,categoryExcelVo,CategoryExcelVo.class);
        categoryExcelVoList.add(categoryExcelVo);
    }
    //写出数据到游览器端
    EasyExcel.write(response.getOutputStream(),CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);
} catch (IOException e) {
    e.printStackTrace();
}
    }

    @Override
    public void importData(MultipartFile file) {
        // 使用EasyExcel解析数据
        try {
            List<CategoryExcelVo> categoryExcelVoList = EasyExcel.read(file.getInputStream()).head(CategoryExcelVo.class).sheet().doReadSync();
            if(!CollectionUtils.isEmpty(categoryExcelVoList)) {
                List<Category> categoryList = new ArrayList<>(categoryExcelVoList.size());
                for(CategoryExcelVo categoryExcelVo : categoryExcelVoList) {
                    Category category = new Category();
                    BeanUtils.copyProperties(categoryExcelVo, category, Category.class);
                    categoryList.add(category);
                }
                this.saveBatch(categoryList);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //=========================前台页面接口=========================

    @Override
    public List<CategoryVo> getOnecategory() {
        List<Category> allCategoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, 0));
        return allCategoryList.stream().map(item -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(item, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<CategoryVo> tree() {

        //查询所有分类数据
        List<CategoryVo> categoryVoList = new ArrayList<>(); //一共703条

        //类型转换
        List<Category> categoryAllList = this.list();
        if (!CollectionUtils.isEmpty(categoryAllList)){
            for (Category category : categoryAllList) {
                CategoryVo vo = new CategoryVo();
                BeanUtils.copyProperties(category,vo);
                categoryVoList.add(vo);
            }
        }
        //构建树结构,组装成父子关系
     List<CategoryVo> treeVoList=   CategoryHelper.buildTree(categoryVoList);
        return treeVoList;
    }
}
